<?php

/*
 * To change this template, choose Tools | Templates
 * and open the template in the editor.
 */

/**
 * Description of Feed
 *
 * @author QuangKhoi
 */
class Signal {

    public $signalID;
    public $userID;
    public $streamID;
    public $signalType;

    /**
     *
     * @var DateTime
     */
    public $date;
    public $gender;
    public $tag;
    public $sentiment;
    public $shareCount;
    public $retweetCount;
    public $message;
    public $messageID;
    public $image;
    public $author;
    public $imageDescription;

    public function __get($name) {
        return $this->$name;
    }

    public function __set($name, $value) {
        $this->$name = $value;
    }

    public function __constructor() {
        
    }

    /**
     * Constructor read signal from database
     * @param Int $id
     */
    public static function getById($id) {
        //Get feed by ID
        //$this->signalID = 
        //$this->userID = 
        //$this->streamID = 
        //$this->signalType = 
        //$this->date =
        //$this->gender = 
        //$this->tag =
        //$this->sentiment = 
        //$this->sharecount = 
        //$this->message = 

        $instance = new self();
        $db = Database::getInstance();
        $result = $db->query("SELECT * FROM signals WHERE signalid = '$id'");
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 1) {
                $rows = $result->dataTable->rows[0];
                $instance->signalID = $rows["signalid"];
                $instance->userID = $rows["userid"];
                $instance->streamID = $rows["streamid"];
                $instance->signalType = $rows["signaltype"];
                $instance->date = new DateTime(($rows["date"]));
                $instance->gender = $rows["gender"];
                $instance->tag = $rows["tag"];
                $instance->sentiment = $rows["sentiment"];
                $instance->shareCount = $rows["sharecount"];
                $instance->retweetCount = $rows["retweetcount"];
                $instance->messageID = $rows["messageid"];
                return $instance;
            } else {
                return NULL;
            }
        } else {
            $controller = new ErrorController(new Error(), new ErrorView, $result->returnCode, $result->message);
            $controller->returnError();
            return NULL;
        }
    }

    /**
     * Constructor read signal from database
     * @param Int $id
     */
    public static function withId($id) {
        //Get feed by ID
        //$this->signalID = 
        //$this->userID = 
        //$this->streamID = 
        //$this->signalType = 
        //$this->date =
        //$this->gender = 
        //$this->tag =
        //$this->sentiment = 
        //$this->sharecount = 
        //$this->message = 

        $instance = new self();
        $db = Database::getInstance();
        $result = $db->query("SELECT * FROM signals WHERE signalid = '$id'");
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 1) {
                $rows = $result->dataTable->rows[0];
                $instance->signalID = $rows["signalid"];
                $instance->userID = $rows["userid"];
                $instance->streamID = $rows["streamid"];
                $instance->signalType = $rows["signaltype"];
                $instance->date = new DateTime(($rows["date"]));
                $instance->gender = $rows["gender"];
                $instance->tag = $rows["tag"];
                $instance->sentiment = $rows["sentiment"];
                $instance->shareCount = $rows["sharecount"];
                $instance->retweetCount = $rows["retweetcount"];
                $instance->messageID = $rows["messageid"];
                $instance->message = Message::withId($rows["messageid"]);
                $instance->text = self::parseQuote(self::parseAllImages($instance->message->getText(), 0));
                $instance->mailText = self::mailQuote($instance->message->getText());
                $instance->textOnly = self::removeLink($instance->message->getText());
                return $instance;
            } else {
                return NULL;
            }
        } else {
            $controller = new ErrorController(new Error(), new ErrorView, $result->returnCode, $result->message);
            $controller->returnError();
            return NULL;
        }
    }

    public static function withMessageId($messageId) {
        
    }

    /**
     * Store item as a signal in db
     * @param ZMessageItem $item
     * @param Stream $stream
     */
    public static function withItem($item, $stream) {
        //$instance->signalID = ;
        $instance = new self();
        $instance->userID = $stream->userId;
        $instance->streamID = $stream->streamId;
        $instance->signalType = $item->getSource();
        $instance->date = new DateTime($item->getTime());
        $instance->messageID = $item->getId();
        //$instance->gender = $item->;
        //$instance->tag = ;
        $instance->sentiment = 0;
        $instance->sharecount = 0;
        $instance->message = $item;
        $instance->image = self::parseImage($item->getLead(), 0);
        $instance->lead = self::parseQuote(self::parseAllImages($item->getLead(), 0));
        $instance->text = self::removeLink($item->getText());
        $instance->author = $item->getAuthor();
        return $instance;
    }

    public static function parseImage($message, $start) {
        //find first "[img "
        $imgPos = strpos($message, "[img", $start);
        if ($imgPos === false)
            return null;

        //start of url
        $httpPos = strpos($message, "(http", $imgPos);
        $httpEndPos = strpos($message, ")", $httpPos);
        $image = substr($message, $httpPos + 1, $httpEndPos - $httpPos - 1);
        $nextPos = strpos($message, "]", $imgPos);
        $imageDescription = substr($message, $imgPos + 5, $nextPos - $imgPos - 5);
        //basic filter
        if ((strpos($image, ".jpg") || strpos($image, ".jpeg")) || strpos($image, ".png") && !strpos($image, ".gif"))
            return $image;
        else
            return self::parseImage($message, $imgPos + 5);
    }

    public static function parseAllImages($message, $start) {
        return preg_replace('#\[img(.*?)\]#i', '', $message);
    }

    public static function parseQuote($message) {
        $message = str_replace("(quote)", '<blockquote><a>show quote</a><div>', $message);
        $message = str_replace("(etouq)", '</div></blockquote>', $message);
        return $message;
    }

    public static function mailQuote($message) {
        $message = str_replace("(quote)", '<blockquote><div>', $message);
        $message = str_replace("(etouq)", '</div></blockquote>', $message);
        return preg_replace('#(\A|[^=\]\'"a-zA-Z0-9])\((http[s]?://(.+?)/[^()<>\s]+)\)#i', '', $message);
    }

    public static function parseLinks($message) {
        return $message = trim(preg_replace("#([> ])(http[s]?://[^ ]+)#i", '\\1 (\\2)', ' ' . $message . ' '));
    }

    public static function withData($messageID, $streamId, $signalType = 1, $date = "", $gender = 0, $tag = "", $sentiment = "", $shareCount = 0) {
        $instance = new self();
        $instance->userID = User::getCurrentUserId();
        $instance->messageID = $messageID;
        $instance->streamID = $streamId;
        $instance->signalType = $signalType;
        if ($date != '')
            $instance->date = new DateTime($date);
        else
            $instance->date = new DateTime();
        $instance->gender = $gender;
        $instance->tag = $tag;
        $instance->sentiment = $sentiment;
        $instance->sharecount = $shareCount;
        return $instance;
    }

    public static function getId($messageId) {
        $db = Database::getInstance();
        $userId = User::getCurrentUserId();
        $result = $db->query("SELECT * FROM signals WHERE userid = '$userId' AND messageid = '$messageId'");
        if ($result->returnCode == 200) {
            if ($result->dataTable->numOfRow == 1) {
                $row = $result->dataTable->rows[0];
                return $row["signalid"];
            }
        }
        return 0;
    }

    public function findTag() {
        return Tag::getTag($this->message->getId(), $this->streamID);
    }

    public function findTask() {
        if ($this->messageID)
            return Task::getTask($this->messageID);
        return Task::getTask($this->message->getId());
    }

    public static function removeLink($message) {
        $message = str_replace("(quote)", 'quote<br>', $message);
        $message = str_replace("(etouq)", '<br>', $message);
        return preg_replace('#\[img(.*?)\]#i', '', $message);
        //return preg_replace('#(\A|[^=\]\'"a-zA-Z0-9])(http[s]?://(.+?)/[^()<>\s]+)#i', '', $message);
    }
    
    public static function removeLinkForEmail($message) {
        $message = preg_replace('#\(quote\)(.+)\(etouq\)#i', '', $message);
        return preg_replace('#\((https?://(.+))\)#i', '', preg_replace('#\[img(.*?)\]#i', '', $message));
        //return preg_replace('#(\A|[^=\]\'"a-zA-Z0-9])(http[s]?://(.+?)/[^()<>\s]+)#i', '', $message);
    }

    public static function removeImage($message) {
        $imgPos = strpos($message, "[img", 0);
        if ($imgPos === false)
            return $message;

        //start of url
        $httpPos = strpos($message, "(http", $imgPos);
        $httpEndPos = strpos($message, ")", $httpPos);
        $image = substr($message, $httpPos + 1, $httpEndPos - $httpPos - 1);
        $nextPos = strpos($message, "]", $imgPos);
        $imageDescription = substr($message, $imgPos + 5, $nextPos - $imgPos - 5);

        //replace
        $strNeedToReplace = substr($message, $imgPos, $httpEndPos + 1 - $imgPos);
        $strToReplace = '';
        $message = str_replace($strNeedToReplace, $strToReplace, $message);
        return self::parseAllImages($message, $imgPos + strlen($strToReplace));
    }

}

?>
